package com.appBase.tools;


import java.net.InetSocketAddress;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.stream.ChunkedWriteHandler;

public class NettyServer {

    private static NioEventLoopGroup bossGroup;
    private static NioEventLoopGroup workerGroup;

    public static void start(String basePath) {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bossGroup =new NioEventLoopGroup();
        workerGroup =new NioEventLoopGroup();
        bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) {
                        ch.pipeline().addLast(new HttpRequestDecoder())
                                .addLast(new HttpObjectAggregator(65536))// 目的是将多个消息转换为单一的request或者response对象
                                .addLast(new HttpResponseEncoder())
                                .addLast(new ChunkedWriteHandler())//目的是支持异步大文件传输（）
                                .addLast("file-handler", new FileServerHandler(basePath))
                                .addLast("handler", new ServerHandler(false));
                    }
                });
        ChannelFuture future = bootstrap.bind(new InetSocketAddress(53881));
        future.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                if (channelFuture.isSuccess()) {
                    System.out.println("Server bound 8000");
                } else {
                    System.err.println("Bind attempt failed");
                    channelFuture.cause().printStackTrace();
                }
            }
        });
    }

    public static void stop() {
        if (bossGroup != null) {
            bossGroup.shutdownGracefully();
        }
        if (workerGroup != null) {
            workerGroup.shutdownGracefully();
        }
    }
}
